import { useEffect, useRef } from 'react';
import { useSettingsStore } from '@/store/settings';
import type { ThemeMode } from '@/types/common/base';

/**
 * 系统主题监听Hook
 * @description 监听系统主题变化并自动更新应用主题
 */
export const useSystemTheme = () => {
  const mediaQueryRef = useRef<MediaQueryList | null>(null);
  const handlerRef = useRef<((e: MediaQueryListEvent) => void) | null>(null);
  
  const { followSystemTheme, themeMode, setThemeMode } = useSettingsStore(state => ({
    followSystemTheme: state.followSystemTheme,
    themeMode: state.themeMode,
    setThemeMode: state.setThemeMode
  }));

  useEffect(() => {
    // 只在浏览器环境中执行
    if (typeof window === 'undefined' || !window.matchMedia) {
      return;
    }

    // 清理之前的监听器
    if (mediaQueryRef.current && handlerRef.current) {
      mediaQueryRef.current.removeEventListener('change', handlerRef.current);
    }

    // 如果不跟随系统主题，不需要监听
    if (!followSystemTheme || themeMode !== 'auto') {
      return;
    }

    // 创建媒体查询
    mediaQueryRef.current = window.matchMedia('(prefers-color-scheme: dark)');
    
    // 创建事件处理器
    handlerRef.current = (e: MediaQueryListEvent) => {
      // 使用防抖避免频繁更新
      const newTheme: ThemeMode = e.matches ? 'dark' : 'light';
      setThemeMode(newTheme);
    };

    // 添加监听器
    mediaQueryRef.current.addEventListener('change', handlerRef.current);

    // 立即检查当前系统主题
    const currentSystemTheme: ThemeMode = mediaQueryRef.current.matches ? 'dark' : 'light';
    if (themeMode === 'auto' || (themeMode !== 'auto' && themeMode !== currentSystemTheme)) {
      setThemeMode(currentSystemTheme);
    }

    // 清理函数
    return () => {
      if (mediaQueryRef.current && handlerRef.current) {
        mediaQueryRef.current.removeEventListener('change', handlerRef.current);
      }
      mediaQueryRef.current = null;
      handlerRef.current = null;
    };
  }, [followSystemTheme, themeMode, setThemeMode]);

  /**
   * 获取当前系统主题
   */
  const getCurrentSystemTheme = (): ThemeMode => {
    if (typeof window !== 'undefined' && window.matchMedia) {
      return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
    }
    return 'light';
  };

  return {
    currentSystemTheme: getCurrentSystemTheme(),
    isListening: followSystemTheme && themeMode === 'auto'
  };
};